#pragma once
#include <iostream>
#include "log.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <string>
#include <unistd.h>

class tcpclient
{
public:
    tcpclient(string serverIp, uint16_t serverPort)
        : _serverIp(serverIp), _serverPort(serverPort)
    {
        // init();
    }
    ~tcpclient()
    {
    }

    void init()
    {
        // socket
        _socketfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_socketfd == -1)
        {
            log(ERROR, "socket create fail");
            exit(-1);
        }
        // log(NOTICE, "socket success");
    }

    void run()
    {
        // connect
        sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_serverPort);
        server.sin_addr.s_addr = inet_addr(_serverIp.c_str());

        // 发送信息到服务端并接受返回信息
        while (true)
        {
            int count = 5;
            bool nect = false;
            while (!nect && count) // 重连功能
            {
                init();
                int ret_con = connect(_socketfd, (sockaddr *)&server, sizeof(server));
                if (ret_con == -1)
                {
                    // log(WORNING, "connect serverce fail");
                    cout << "try connect serverce fail " << count << endl;
                    // exit(-1);
                }
                else
                {
                    nect = true;
                    break;
                }
                // log(NOTICE, "connect success");
                count--;
                sleep(2);
            }
            if (count == 0)
            {
                cout << "client quit" << endl;
                exit(-1);
            }
            cout << "请输入>>";
            string sendMsg;
            getline(cin, sendMsg);

            write(_socketfd, sendMsg.c_str(), sendMsg.size() + 1);

            char recvMsg[1024];
            int n = read(_socketfd, recvMsg, sizeof(recvMsg) - 1);
            if (n == 0)
            {
                log(NOTICE, "server close socket");
                continue;
                // exit(-1);
            }
            recvMsg[n] = '\0';
            cout << recvMsg << endl;
        }
    }

private:
    int _socketfd;
    string _serverIp;
    uint16_t _serverPort;
};
